package xin.yangshuai.juc01.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xin.yangshuai.juc01.service.ThreadPoolService;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
public class ThreadPoolController {

    public static final Logger logger = LoggerFactory.getLogger(ThreadPoolController.class);

    @Autowired
    private ThreadPoolService threadPoolService;

    @Qualifier("taskExecutor1")
    @Autowired
    private Executor taskExecutor1;

    @RequestMapping("threadPoolInfo")
    public String threadPoolInfo() {

        threadPoolService.threadPoolInfo();
        return "hello world";
    }

    @RequestMapping("threadPoolTest")
    public String threadPoolTest() {

        for (int i = 0; i < 200; i++) {

            logger.info("调用异步方法开始，index：{}", i);
            threadPoolService.threadPoolTest(i);
//            logger.info("调用异步方法结束，index：{}", i);

        }

        return "hello world";
    }

    @RequestMapping("threadPoolTest1")
    public String threadPoolTest1() {

        for (int i = 0; i < 20; i++) {
            threadPoolService.threadPoolTest1(i);
        }

        return "hello world";
    }

    @RequestMapping("threadPoolTest2")
    public String threadPoolTest2(int size) {

        for (int i = 0; i < size; i++) {

            if (!checkThreadPoolUsable(taskExecutor1)) {
                throw new RuntimeException("当前任务过多");
            }

            threadPoolService.threadPoolTest1(i);
        }

        return "hello world";
    }

    /**
     * 检查线程池是否可用
     *
     * @param executor
     * @return
     */
    private boolean checkThreadPoolUsable(Executor executor) {

        if (executor == null) {
            return false;
        }

        if (executor instanceof ThreadPoolTaskExecutor) {
            ThreadPoolTaskExecutor threadTask = (ThreadPoolTaskExecutor) executor;
            ThreadPoolExecutor threadPoolExecutor = threadTask.getThreadPoolExecutor();

            long taskCount = threadPoolExecutor.getTaskCount();
            long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
            int corePoolSize = threadPoolExecutor.getCorePoolSize();
            int maximumPoolSize = threadPoolExecutor.getMaximumPoolSize();
            int activeCount = threadPoolExecutor.getActiveCount();
            int queueSize = threadPoolExecutor.getQueue().size();
            int remainingCapacity = threadPoolExecutor.getQueue().remainingCapacity();

            if (activeCount == maximumPoolSize && remainingCapacity <= 0) {
                logger.info("|---------------------------------------------------");
                logger.info("|-提交任务数：{}", taskCount);
                logger.info("|-完成任务数：{}", completedTaskCount);
                logger.info("|-核心线程数：{}", corePoolSize);
                logger.info("|-最大线程数：{}", maximumPoolSize);
                logger.info("|-正在执行任务的线程数：{}", activeCount);
                logger.info("|-队列中的任务数：{}", queueSize);
                logger.info("|-队列中剩余可用的容量：{}", remainingCapacity);
                logger.info("|----------------------------------------------------");

                return false;
            }
        }

        return true;
    }
}
